<!--
 * @Author: zhangjingyu
 * @Date: 2020-11-04 19:43:11
 * @LastEditors: zhangjingyu
 * @LastEditTime: 2021-01-04 13:46:50
 * @Description: 基础曲线定义
-->
<template>
  <!-- 基础曲线定义页面 -->
  <div>
    <el-row class="baceCurveDefinition container">
      <el-col style="margin-right:10px;" class="content-left">
        <!-- 操作区域 -->
        <upper-template
          @search="searchForm.page=1,searchFunc()"
          @clear="
            (searchForm.curveCode = ''),
              (searchForm.curveName = ''),
              (searchForm.dimCurrencyID = '')
          "
        >
          <!-- 操作按钮区 -->
          <template slot="buttonArea">
            <el-button @click="addFunc()">新增</el-button>
            <el-button @click="editFunc()">编辑</el-button>
            <el-button @click="delFunc()">删除</el-button>
          </template>

          <!-- 搜索区 -->
          <template slot="searchArea">
            <el-form
              :model="searchForm"
              ref="searchForm"
              label-width="67px"
              label-position="left"
              size="mini"
            >
              <el-form-item label="编号：" prop="curveCode">
                <el-input
                  v-model="searchForm.curveCode"
                  placeholder="请输入编号"
                ></el-input>
              </el-form-item>
              <el-form-item label="名称：" prop="curveName">
                <el-input
                  v-model="searchForm.curveName"
                  placeholder="请输入名称"
                ></el-input>
              </el-form-item>
              <el-form-item label="币种：" prop="dimCurrencyID">
                <el-input
                  v-model="searchForm.dimCurrencyID"
                  placeholder="请输入币种编号"
                ></el-input>
              </el-form-item>
            </el-form>
          </template>
          <!-- 显示隐藏区 -->
          <template slot="columnHide">
            <el-checkbox-group v-model="checkList">
              <el-checkbox
                v-for="item in textData"
                :label="item.label"
                :key="item.prop"
                >{{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
          </template>
        </upper-template>
        <el-table
          ref="multipleTable"
          :data="tableData"
          @row-click="authorizeFor"
        >
          <el-table-column
            width="55"
            type="selection"
            
          ></el-table-column>
          <el-table-column prop="curveCode" label="编号" v-if="columnState[0]"  show-overflow-tooltip >
          </el-table-column>
          <el-table-column prop="curveName" label="名称 " v-if="columnState[1]" show-overflow-tooltip >
          </el-table-column>
          <el-table-column
            prop="dimCurrency.currencyCode"
            label="币种编号"
            v-if="columnState[2]"
          >
          </el-table-column>
          <el-table-column
            prop="termStructDef.structureName"
            label="期限结构 "
            show-overflow-tooltip 
            v-if="columnState[3]"
          >
          </el-table-column>
          <el-table-column
            prop="accruBasis"
            label="计息基础代码"
            v-if="columnState[4]"
            :formatter="
              row => this.$getLabel(row.accruBasis, this.accruBasisList)
            "
          >
          </el-table-column>
          <el-table-column
            prop="interpolationFlag"
            label="是否插值"
            v-if="columnState[5]"
            :formatter="row => (row.interpolationFlag == 1 ? '是' : '否')"
          >
          </el-table-column>
          <el-table-column
            prop="interpolationWay"
            label="插值方式"
            v-if="columnState[6]"
            :formatter="
              row =>
                this.$getLabel(row.interpolationWay, this.interpolationWayList)
            "
          >
          </el-table-column>
          <el-table-column
            prop="affirmFre"
            label="确认频率 "
            v-if="columnState[7]"
            :formatter="
              row => this.$getLabel(row.affirmFre, this.affirmFreList)
            "
          >
          </el-table-column>
          <el-table-column prop="creator" label="创建人" v-if="columnState[8]" :formatter="row=>row.creator||'-'">
          </el-table-column>
          <el-table-column
            prop="createdTm"
            label="创建时间"
             show-overflow-tooltip 
            sortable
            v-if="columnState[9]"
            :formatter="row => timeFormat(row.createdTm)"
          >
          </el-table-column>
          <el-table-column
            prop="modifier"
            label="修改人"
            v-if="columnState[10]"
            :formatter="row=>row.modifier||'-'"
          >
          </el-table-column>
          <el-table-column
            prop="modifiedTm"
            label="修改时间"
             show-overflow-tooltip 
            sortable
            v-if="columnState[11]"
            :formatter="row => timeFormat(row.modifiedTm)"
          >
          </el-table-column>
        </el-table>
        <pagination
          @size-change="sizeChange"
          @current-change="pageChange"
          @refresh="searchFunc"
          :current-page="searchForm.page"
          :page-size="searchForm.size"
          :total="total"
        ></pagination>
      </el-col>
    </el-row>
    <el-dialog
      v-dialogDrag
      :title="saveTitles[saveFlg - 1]"
      :visible.sync="addOrEdit"
      width="600px"
    >
      <el-form
        :model="saveForm"
        ref="saveForm"
        label-width="110px"
        label-position="left"
        :rules="saveFormRules"
      >
        <el-form-item label="曲线编号:" prop="curveCode">
          <el-input
            v-model="saveForm.curveCode"
            maxlength="40"
            :disabled="saveFlg == 2"
          ></el-input>
        </el-form-item>
        <el-form-item label="曲线名称:" prop="curveName">
          <el-input v-model="saveForm.curveName" maxlength="64"></el-input>
        </el-form-item>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="确认频率:" prop="affirmFre">
              <el-select v-model="saveForm.affirmFre" placeholder="请选择">
                <el-option
                  v-for="item in affirmFreList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="币种:"
              label-position="right"
              prop="dimCurrencyCode"
            >
              <el-select
                v-model="saveForm.dimCurrencyCode"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in ccyList"
                  :key="item.currencyCode"
                  :label="item.currencyName"
                  :value="item.currencyCode"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-col :span="24">
          <el-form-item label="是否插值:" prop="interpolationFlag">
            <el-radio-group
              v-model="saveForm.interpolationFlag"
              @change="intFlagChange"
            >
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="saveForm.interpolationFlag == '1'">
          <el-form-item label="插值方式:" prop="interpolationWay">
            <el-radio-group v-model="saveForm.interpolationWay" size="mini">
              <el-radio
                v-for="item in interpolationWayList"
                :label="item.value"
                :key="item.value"
                border
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="期限结构:" prop="structureCode">
            <el-select
              v-model="saveForm.structureCode"
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in structureList"
                :key="item.structureCode"
                :label="item.structureName"
                :value="item.structureCode"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="计息基础代码:" prop="accruBasis">
            <el-select
              v-model="saveForm.accruBasis"
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in accruBasisList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveFunc">确 定</el-button>
        <el-button @click="addOrEdit = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import onlyOneSearch from "@/components/onlyOneSearch";
import moment from "moment";
import { publicManage_pub } from "@/api/index";
export default {
  data() {
    return {
      addOrEdit: false, // 新增/编辑/查看弹窗
      isModuleData: false, //同步模块数据弹窗
      serachMore: false,
      isProConfig: false, //工程表配置弹窗
      saveFlg: 1, // 1:新增，2：编辑，3查看,
      saveTitles: ["添加基础定义表信息", "修改基础定义表信息"],

      // 币种
      ccyList: [],
      // 确认频率list
      affirmFreList: [],
      // 期限结构
      structureList: [],
      // 计息基础代码
      accruBasisList: [],
      // 差值方式
      interpolationWayList: [],
      searchForm: {
        page: 1,
        size: 15
      },
      total: 0,
      saveForm: {
        curveCode: "",
        curveName: "",
        dimCurrencyCode: "",
        structureCode: "",
        accruBasis: "",
        affirmFre: "",
        interpolationFlag: "1",
        interpolationWay: ""
      },
      searchFF: {},
      saveFormRules: {
        curveCode: [
          { required: true, message: "曲线编码为必输项", trigger: "blur" },
          {
            pattern: /^[0-9a-zA-Z_]{0,30}$/,
            message: "请输入1-30位字母、数字或_",
            trigger: "blur"
          },
          { validator: this.curveCodeValid, trigger: "blur" }
        ],
        curveName: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[\u4E00-\u9FA5A-Za-z0-9_]{1,64}$/,
            message: "只能输入1-64位英文字母、数字、中文_",
            trigger: "blur"
          }
        ],
        accruBasis: [
          { required: true, message: "请选择计息基础代码项", trigger: "blur" }
        ],
        structureCode: [
          { required: true, message: "请选择期限结构", trigger: "blur" }
        ],
        affirmFre: [
          { required: true, message: "请选择确认频率", trigger: "blur" }
        ],
        dimCurrencyCode: [
          { required: true, message: "请选择币种", trigger: "blur" }
        ],
        interpolationFlag: [
          { required: true, message: "请选择是否插值", trigger: "blur" }
        ]
      },

      checkList: [],
      // 列隐藏
      textData: [
        { label: "编号" },
        { label: "名称 " },
        { label: "币种编号" },
        { label: "期限结构" },
        { label: "计息基础代码" },
        { label: "是否插值" },
        { label: "插值方式" },
        { label: "确认频率" },
        { label: "创建人 " },
        { label: "创建时间" },
        { label: "修改人 " },
        { label: "修改时间 " }
      ],
      // 获取table的数据
      tableData: []
    };
  },
  components: {
    onlyOneSearch
  },
  created() {
    this.checkListInit();
    this.getAllDict();
    this.$nextTick(() => {
      this.searchFunc();
    });
    console.log(this.tableData, "模拟数据");
  },
  computed: {
    columnState() {
      console.log(this.checkList);
      let arr = [],
        arr1 = this.textData,
        arr2 = this.checkList;
      for (let i = 0; i < arr1.length; i++) {
        let flg = false;
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label === arr2[j]) {
            flg = true;
          }
        }
        arr.push(flg);
      }
      return arr;
    }
  },
  mounted() {
    // this.getList();
  },
  watch: {
     addOrEdit() {
      // 窗口打开或关闭清除校验结果
      if (this.$refs.saveForm) {
        this.$refs.saveForm.clearValidate();
      }
    },
  },
  methods: {
    checkListInit() {
      this.checkList = this.textData.map(v => {
        return v.label;
      });
    },
    // 获取可用币种
    getCcyList() {
      publicManage_pub
        .currencyManageQueryAvailable({ page: 1, size: 999 })
        .then(res => {
          this.ccyList = res.data;
        });
    },
    // 获取字典
    getAllDict() {
      this.getCcyList();

      this.$getDict("sys_cp_accru_basis_cd").then(res => {
        if (res.code == 200) {
          this.accruBasisList = res.datas;
        }
      });

      this.$getDict("sys_cp_conf_way").then(res => {
        if (res.code == 200) {
          this.interpolationWayList = res.datas;
        }
      });
      this.$getDict("cpm_frequency").then(res => {
        if (res.code == 200) {
          this.affirmFreList = res.datas;
        }
      });
      publicManage_pub.baseCurveDefFindTermStruct().then(res => {
        if (res) {
          this.structureList = res;
        }
      });
    },
    intFlagChange(val) {
      if (val == "1") {
        this.$nextTick(() => {
          this.saveForm.interpolationWay = this.interpolationWayList[0].value;
        });
      } else {
        this.saveForm.interpolationWay = "";
      }
      this.$forceUpdate();
    },
    // 校验code唯一性
    curveCodeValid(rule, value, callback) {
      if (this.saveFlg != 1) {
        callback();
        return;
      }
      let data = { id: value };
      publicManage_pub.baseCurveDefCheckExists(data).then(res => {
        if (res.success) {
          callback(new Error("编号已存在"));
          } else {
          callback();
        }
      });
    },
    searchFunc() {
      let data = this.searchForm;
      publicManage_pub.baseCurveDefQuery(data).then(res => {
        if (res.code == 200) {
          this.tableData = res.data;
          this.total = res.count;
        }
      });
      console.log(this.searchForm);
    },
    addFunc() {
      this.saveFlg = 1;
      for (let k in this.saveForm) {
        this.saveForm[k] = "";
      }
      this.addOrEdit = true;
    },
    editFunc() {
      this.saveFlg = 2;
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行修改");
      }
      let row = selection[0];
      let form = { ...row };
      this.saveForm.curveCode = form.curveCode;
      this.saveForm.curveName = form.curveName;
      this.saveForm.dimCurrencyCode = form.dimCurrency.currencyCode;
      this.saveForm.structureCode = form.termStructDef.structureCode;
      this.saveForm.accruBasis = form.accruBasis;
      this.saveForm.affirmFre = form.affirmFre;
      this.saveForm.interpolationFlag = form.interpolationFlag;
      this.saveForm.curveName = form.curveName;
      this.saveForm.interpolationWay = form.interpolationWay;
      console.log(this.saveForm);
      this.addOrEdit = true;
    },
    saveFunc() {
      let data = this.saveForm;
      this.$refs["saveForm"].validate(valid => {
        if (valid) {
          publicManage_pub.baseCurveDefSave(data).then(res => {
            if (res.code == 200) {
              this.$message.success("保存成功");
              this.searchFunc();
              this.addOrEdit = false;
            } else {
              this.$message.error(res.message || "保存失败");
            }
          });
        }
      });
    },
    delFunc() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的数据");
      }
      this.$confirm("您确定要删除选中曲线吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data ={ids:selection.map(v=>v.curveCode)}
          publicManage_pub.baseCurveDefDelete(data).then(res => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message||"删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    handleNodeClick() {
      let nodes = this.$refs.configTree.getCheckedNodes();
      console.log(nodes);
    },
    caliberProjectNameFormatter(row) {
      return row.caliberProject.caliberProjectName;
    },
    getList() {
      // publicManage.query("我的参数").then(res => {
      //   console.log(res);
      // });
    },
    authorizeFor(row) {
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
      }
      this.$refs.multipleTable.toggleRowSelection(row, true);
    },
    // 重新加载
    reload() {
      this.isModuleData = true;
    },
    timeFormat(val) {
      if (val) return moment(val).format("YYYY-MM-DD HH:mm:ss")
      else return '-';
    },
    sizeChange(val) {
      this.searchForm.size = val;
      this.searchFunc();
    },
    pageChange(val) {
      this.searchForm.page = val;
      this.searchFunc();
    }
  }
};
</script>

<style lang="scss" scoped>
.dialogSearchBox {
  header {
    text-align: center;
    span {
      margin: 0 20px;
    }
  }
}
</style>